package org.example.demopaper.service;

import org.example.demopaper.dao.UserDao;
import org.example.demopaper.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.mindrot.jbcrypt.BCrypt;

@Service
public class UserService {

    private final UserDao userDao;

    @Autowired
    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    // 注册新用户
    public boolean register(String username, String password) {
        if (userDao.findByUsername(username) != null) {
            return false; // 用户名已存在
        }
        // 使用BCrypt对密码进行加密
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt(12));
        User newUser = new User(username, hashedPassword);
        userDao.save(newUser);
        return true;
    }

    // 用户登录验证
    public boolean login(String username, String password) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            return false; // 用户不存在
        }
        // 使用BCrypt验证密码
        return BCrypt.checkpw(password, user.getPassword());
    }
}